package com.wms.oms.controller.weixin;


import com.wms.common.core.constant.Constants;
import com.wms.common.core.utils.TreeUtil;
import com.wms.common.core.utils.bean.BeanUtils;
import com.wms.common.core.web.controller.BaseController;
import com.wms.common.core.web.domain.AjaxResult;
import com.wms.oms.api.domain.ProductCategoryDTO;
import com.wms.oms.domain.ProductCategory;
import com.wms.oms.domain.dto.ProductCategoryTree;
import com.wms.oms.service.IProductCategoryService;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 小程序商品分类
 */
@RestController
@RequestMapping("/wx/category")
public class ProductCategoryWxController extends BaseController {


    @Autowired
    private IProductCategoryService productCategoryService;



    @GetMapping("/firstList")
    public AjaxResult firstList()
    {
        List<ProductCategory> list = productCategoryService.selectProductCategoryFirstList();
        return AjaxResult.success(list);
    }

    @GetMapping("/list")
    public AjaxResult list(ProductCategory productCategory)
    {
        List<ProductCategory> list = productCategoryService.selectProductCategoryList(productCategory);
        return AjaxResult.success(getTree(list));
    }


    /**
     * 构建树
     *
     * @param entitys
     * @return
     */
    private List<ProductCategoryTree> getTree(List<ProductCategory> entitys) {
        List<ProductCategoryTree> treeList = entitys.stream()
                .filter(entity -> !entity.getId().equals(entity.getParentId()))
                .sorted(Comparator.comparingInt(ProductCategory::getSort))
                .map(entity -> {
                    ProductCategoryTree node = new ProductCategoryTree();
                    BeanUtils.copyProperties(entity, node);
                    node.setPicUrl(entity.getIcon());
                    return node;
                }).collect(Collectors.toList());
        return TreeUtil.build(treeList, Constants.PARENT_ID);
    }
}
